// pages/address/list/index.js
//导入接口api函数
import {
  reqAddressList,
  reqDeleteAddress
} from "../../../api/address"
import {
  swipeCellBehavior
} from "@/behaviors/swipeCell"
const app = getApp()
Page({
  behaviors: [swipeCellBehavior],
  // 页面的初始数据
  data: {
    addressList: []
  },

  // 去编辑页面
  toEdit(event) {
    //获取要更新的收获地址的id
    const {
      id
    } = event.currentTarget.dataset
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },
  //获取收获地址lie
  async getAddressList() {
    const {
      data: addressList
    } = await reqAddressList()
    this.setData({
      addressList
    })
  },

  //删除地址
  async delAddress(event) {
    const {
      id
    } = event.currentTarget.dataset
    const modalRes = await wx.modal({
      content: "你确认删除该地址嘛？"
    })
    if (modalRes) {
      await reqDeleteAddress(id)
      wx.toast({
        title: "收获地址删除成功"
      })
      this.getAddressList()
    }
  },
  //更新收货地址
  changeAddress(event) {
    //需要判断是否是从结算支付页面进入的收获地址页面
    //如果是，才能够获取收获地址
    if (this.flag !== "1") return
    const addressId = event.currentTarget.dataset.id
    //需要从收获地址列表中根据收获地址id查询到收获地址的详情信息
    const selectAddress = this.data.addressList.find(item => item.id === addressId)
    if (selectAddress) {
      //需要赋值给全局共享的数据
      app.globalData.address = selectAddress
      wx.navigateBack()
    }
  },

  //页面展示时触发
  onShow() {
    this.getAddressList()
  },
  onLoad(options) {
    //接收传递的参数，挂载到页面实例上
    this.flag = options.flag
  }

})